`timescale 1ns / 1ps

module spi_4to3_conv(
    // 4-wire spi
    input  wire 	i_spi_ss,
    input  wire    i_spi_sclk,
    output wire    o_spi_miso,
    input  wire    i_spi_mosi,
    // 3-wire spi sdata
    inout  wire    io_spi_sdata
    );

wire [5 : 0]    edge_sig_cnt;
reg		         sdata_first_bit = 1'b0;
reg		         sdata_is_in = 1'b0;
reg  [4 : 0]     cycle_cnt = 5'd0;

always @(posedge i_spi_sclk)
   if (~i_spi_ss & (cycle_cnt != 'd23))
       cycle_cnt <= cycle_cnt + 'd1;
   else
       cycle_cnt <= 'd0; 

always @(posedge i_spi_sclk)
begin
   if (~i_spi_ss & cycle_cnt == 'd0)
       sdata_first_bit  <= i_spi_mosi;
   else
       sdata_first_bit  <= sdata_first_bit;
end

always @(negedge i_spi_sclk)
begin
	    sdata_is_in <= cycle_cnt >= 6'd16 & ~i_spi_ss & sdata_first_bit;
end

assign	o_spi_miso   = sdata_is_in ? io_spi_sdata : 1'bz;
assign	io_spi_sdata = sdata_is_in ? 1'bz : i_spi_mosi;

endmodule

